package com.haiyi.software.app.basic;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.entity.UserInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

public abstract class ActivityBasicCharmCityListGetCharm extends
		ActivityBasicCharmCityList {

	private final String TAG = "ActivityBasicCharmCityListGetCharm";

	private String str_getGoldCharmURL = "mygold.php";

	private JsonObject myGoldBody = null;

	protected abstract void getMyGoldSuccess(JsonObject myGoldBody);

	protected void getPersonGold() {
		String str_server = this.getResources().getString(R.string.URL);

		String str_requestURL = str_server + str_getGoldCharmURL;

		AsyncHttpClient client = new AsyncHttpClient();

		RequestParams params = new RequestParams();

		params.put("args", getJsonArgs());

		client.setTimeout(60);

		client.post(str_requestURL, params, responseHandler);
	}

	private ResponseHandlerInterface responseHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {
			try {
				String str_jsonReturn = new String(responseBody, "UTF-8");

				Log.i(TAG, str_jsonReturn);

				JsonParser parser = new JsonParser();

				JsonObject jsonResult = parser.parse(str_jsonReturn)
						.getAsJsonObject();

				if (jsonResult.get("state").getAsString().equals("200")) {

					myGoldBody = jsonResult.get("body").getAsJsonObject();

				}

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				myGoldBody = null;
				e.printStackTrace();
			}
			getMyGoldSuccess(myGoldBody);
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根

		}
	};

	private String getJsonArgs() {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();
		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			Log.i("argsJson", s);

			return s;
		} else {
			return null;
		}

	}
}
